import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import Trapezium from '@/components/trapezium';
import Icon from '@/components/layout/Icon';
import { getListApi, getHolidayApi, setHolidayApi } from '@/request/personManage';
// import { holiday } from '@/utils/data';
import { getListApi as getReviewListApi } from '@/request/review';
import UsedEnv from '../usedEnv';

dayjs.locale('zh-cn');

const isoWeek = require('dayjs/plugin/isoWeek');
const weekOfYear = require('dayjs/plugin/weekOfYear');
const isoWeeksInYear = require('dayjs/plugin/isoWeeksInYear');
const isLeapYear = require('dayjs/plugin/isLeapYear');
const weekday = require('dayjs/plugin/weekday');

dayjs.extend(isoWeek);
dayjs.extend(weekOfYear);
dayjs.extend(isoWeeksInYear);
dayjs.extend(isLeapYear);
dayjs.extend(weekday);
let holiday: string[] = [];

const Review = () => {
  const [result3, setResult3] = useState<any[]>([]);
  const [result5, setResult5] = useState<any[]>([]);

  // 获取review人员信息
  const getReviewPersons = async () => {
    const res: any = await getReviewListApi({});
    if (res) {
      setResult5(res);
    }
  };

  const judegDate = (time) => new Date().getTime() > time.getTime();

  const createWeeks = (years) => {
    let weeks7: string[] = [];
    // 年月日是周五的
    let weeks5: string[] = [];
    // 年月日是周三的
    let weeks3: string[] = [];
    // 年月日是周一的
    let weeks1: string[] = [];
    for (let j = 0; j < years.length; j += 1) {
      const dayjs_year: any = dayjs(years[j]);
      const backvalue7: any = dayjs(dayjs_year.isoWeekday(7));
      const backvalue5: any = dayjs(dayjs_year.isoWeekday(5));
      const backvalue3: any = dayjs(dayjs_year.isoWeekday(3));
      const backvalue1: any = dayjs(dayjs_year.isoWeekday(1));
      const count = dayjs_year.isoWeeksInYear(); // 52
      for (let i = 0; i < count; i += 1) {
        weeks7.push(backvalue7.week(i + 1).format('YYYY-MM-DD'));
        weeks5.push(backvalue5.week(i + 1).format('YYYY-MM-DD'));
        weeks3.push(backvalue3.week(i + 1).format('YYYY-MM-DD'));
        weeks1.push(backvalue1.week(i + 1).format('YYYY-MM-DD'));
      }
    }
    weeks1 = weeks1.filter((item) => item);
    weeks3 = weeks3.filter((item) => item);
    weeks5 = weeks5.filter((item) => item);
    weeks7 = weeks7.filter((item) => !holiday.includes(item));
    return {
      weeks7,
      weeks5,
      weeks3,
      weeks1,
      week5_reviews: weeks5.filter((item) => !holiday.includes(item)),
    };
  };

  // const renderR5 = (arr, index, date: string[], person) => {
  //   let i = index;
  //   for (let j = 0; j < date.length; j += 1) {
  //     if (i >= person.length) i = 0;
  //     if (!judegDate(new Date(`${date[j]} 23:59:59`))) {
  //       arr.push({
  //         time: date[j],
  //         name: person[i].name,
  //       });
  //       i += 1;
  //     }
  //   }
  // };

  const renderR3 = (index, date3: string[], date1: string[], date5: string[], person) => {
    let i = index;
    const temp: any = [];
    for (let j = 0; j < date3.length; j += 1) {
      if (i >= person.length) i = 0;
      const last = dayjs(date3[j]).subtract(2, 'day').format('YYYY-MM-DD');
      const end = dayjs(date3[j]).add(2, 'day').format('YYYY-MM-DD');
      if ((!holiday.includes(last) || !holiday.includes(end)) && !holiday.includes(date3[j])) {
        temp.push({
          time: `${last} 至 ${end}`,
          name: person[i].name,
          weekend: end,
        });
        i += 1;
      } else {
        temp.push({
          time: `${last} 至 ${end}`,
          name: person[i].name,
          weekend: end,
        });
      }
    }
    const arr = temp.filter((item: any) => !judegDate(new Date(`${item.weekend as string} 23:59:59`)));
    return arr;
  };

  const renderDate = (persons, leaders) => {
    const result5_c: any = [];
    const next_year = `${dayjs().add(1, 'year').year()}`;
    const { weeks3, weeks5, weeks1, weeks7, week5_reviews } = createWeeks([new Date(), new Date(next_year)]);
    // renderR5(result5_c, 7, week5_reviews, persons);
    const result3_c: any = renderR3(0, weeks3, weeks1, weeks5, leaders);
    console.log(result3_c, 'result3_c');
    setResult3(result3_c);
    // setResult5(result5_c);
  };

  const getPerson = async () => {
    const res: any = await getListApi({});
    const persons = res.filter((item) => item.weight).sort((a, b) => Number(a.weight) - Number(b.weight));
    const leaders = res
      .filter((item) => item.onDuty)
      .sort((a, b) => Number(a.onDuty) - Number(b.onDuty))
      .filter((item) => item.role.roleName === '组长');
    renderDate(persons, leaders);
  };

  const getHoliday = async () => {
    try {
      const r: any = await getHolidayApi();
      const h: string[] = [];
      for (let i = 0; i < r.length; i += 1) {
        const res = r[i].holiday;
        Object.keys(res).forEach((item) => {
          if (res[item].holiday) {
            h.push(`${r[i].year as string}-${item}`);
          }
        });
      }
      holiday = h;
      getPerson();
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getHoliday();
    getReviewPersons();
    // setHolidayApi({ year: '2024' });
  }, []);
  return (
    <div className="review">
      {/* 值班 */}
      <div className="dashboard-box mb10">
        <div className="onduty">
          <div className="onduty-cur">
            <div className="title">本周值班人员</div>
            <div className="person">
              <div>{result3[0]?.name}</div>
              <div className="time">{result3[0]?.time}</div>
            </div>
          </div>
          <div className="onduty-next">
            <div className="title">下周值班人员</div>
            <div className="person">
              <div>{result3[1]?.name}</div>
              <div className="time">{result3[1]?.time}</div>
            </div>
          </div>
        </div>
      </div>
      {/* 代码review */}
      <div className="dashboard-box code-review mb10">
        <Trapezium text="代码Review主讲" actived style={{ marginBottom: '20px' }} />
        <div className="review-person">
          <div className="review-person-list">
            {result5.map((item, index) => (
              <div key={index} className="review-item">
                {index === 0 ? (
                  <div className="prefix-cur">
                    <Icon src={require('@/public/images/mic.png')} width={9} height={12} />
                  </div>
                ) : (
                  <div className="perfix"></div>
                )}
                <div className={['person-item ', index === 0 ? 'person-item-cur' : ''].join('')}>
                  <div className="time">{`${String(item.time)}`}</div>
                  <div className="person-name">{item.name}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      {/* 环境使用 */}
      <div className="dashboard-box use-env-H">
        <Trapezium text="环境使用分布" actived style={{ marginBottom: '20px' }} />
        <UsedEnv />
      </div>
    </div>
  );
};

export default Review;
